import { useEffect, useState } from 'react';
import { Dimensions, ScaledSize } from 'react-native';
import { 
  wp, 
  hp, 
  sp, 
  screenWidth, 
  screenHeight, 
  pixelRatio, 
  isTablet as checkTablet, 
  isLandscape as checkLandscape,
  getDesignBase
} from '../utils/layout';
import { FONT_SIZES, fontSize } from '../utils/fontSize';

// 响应式Hook
export default function useResponsive() {
  // 设备方向
  const [orientation, setOrientation] = useState<'PORTRAIT' | 'LANDSCAPE'>(
    checkLandscape() ? 'LANDSCAPE' : 'PORTRAIT'
  );

  // 是否为平板
  const [isTablet, setIsTablet] = useState(checkTablet());

  // 屏幕尺寸
  const [dimensions, setDimensions] = useState({
    width: screenWidth,
    height: screenHeight,
  });

  // 设计基准
  const [designBase, setDesignBase] = useState(getDesignBase());

  useEffect(() => {
    // 处理屏幕尺寸或方向改变
    const handleDimensionsChange = ({ window }: { window: ScaledSize }) => {
      const isPortrait = window.width < window.height;
      const newOrientation = isPortrait ? 'PORTRAIT' : 'LANDSCAPE';
      const tabletDevice = checkTablet();

      setOrientation(newOrientation);
      setIsTablet(tabletDevice);
      setDimensions({
        width: window.width,
        height: window.height,
      });
      
      // 更新设计基准
      setDesignBase(getDesignBase());
    };

    // 添加监听器
    const subscription = Dimensions.addEventListener('change', handleDimensionsChange);

    // 清理函数
    return () => {
      if (subscription?.remove) {
        subscription.remove();
      }
    };
  }, []);

  return {
    wp,
    hp,
    sp,
    fontSize,
    sizes: FONT_SIZES,
    orientation,
    isTablet,
    dimensions,
    width: dimensions.width,
    height: dimensions.height,
    pixelRatio,
    designBase
  };
} 